package cn.just.dao;

import cn.just.entity.User;
import cn.just.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author wujiaming
 */
public class UserDao {

    /**
     * 注册用户
     * @param user
     */
    public void save(User user) throws SQLException {
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        connect = JDBCUtil.getConnect();
        String sql = "insert into user(userName,password,email)" +
                "values(?,?,?)";
        preparedStatement = connect.prepareStatement(sql);
        preparedStatement.setString(1,user.getUserName());
        preparedStatement.setString(2,user.getPassword());
        preparedStatement.setString(3,user.getEmail());
        preparedStatement.executeUpdate();

        JDBCUtil.close(connect,preparedStatement);
    }

    /**
     * 登录
     */
    public User findUserById(String name,String pwd) throws SQLException {
        Connection connect = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = null;

        connect = JDBCUtil.getConnect();
        String sql = "select oId,userName,password from user where userName=? and password=?";
        preparedStatement = connect.prepareStatement(sql);
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,pwd);

        resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            int oId = resultSet.getInt("oId");
            String userName = resultSet.getString("userName");
            String password = resultSet.getString("password");
            user = new User();
            user.setoId(oId);
            user.setUserName(userName);
            user.setPassword(password);
//            user = new User(oId,name,pwd,null);

        }

        JDBCUtil.close(connect,preparedStatement,resultSet);
        return user;
    }
}
